package com.yupi.project.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.model.entity.InterfaceInfo;
import com.yupi.project.common.ErrorCode;
import com.yupi.project.exception.BusinessException;
import com.yupi.project.mapper.UserInterfaceInfoMapper;
import com.yupi.model.entity.UserInterfaceInfo;
import com.yupi.project.model.vo.InterfaceInfoVO;
import com.yupi.project.service.InterfaceInfoService;
import com.yupi.project.service.UserInterfaceInfoService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author v
* @description 针对表【user_interface_info(用户调用接口关系表)】的数据库操作Service实现
* @createDate 2023-09-27 10:22:14
*/
@Service
public class UserInterfaceInfoServiceImpl extends ServiceImpl<UserInterfaceInfoMapper, UserInterfaceInfo>
    implements UserInterfaceInfoService{

    @Resource
    private InterfaceInfoService interfaceInfoService;

    @Override
    public void validUserInterfaceInfo(UserInterfaceInfo userInterfaceInfo, boolean add) {
        if (userInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long interfaceInfoId = userInterfaceInfo.getInterfaceInfoId();
        Long userId = userInterfaceInfo.getUserId();
        Integer leftNum = userInterfaceInfo.getLeftNum();
        Integer totalNum = userInterfaceInfo.getTotalNum();
        Integer status = userInterfaceInfo.getStatus();
        // 创建时，所有参数必须非空
        if (ObjectUtils.anyNull(interfaceInfoId, userId)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 添加
        if (add) {
            if (interfaceInfoId <= 0 || userId <= 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户或接口不存在");
            }
        }
        if (leftNum < 0 || totalNum < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "剩余次数或总次数不能少于0");
        }
        if (status != 1 && status != 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
    }

    @Override
    public boolean invokeCount(long interfaceInfoId, long userId) {
        // 1. 参数检验
        if (interfaceInfoId <= 0 || userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 2. 判断是否是第一次调用
        LambdaQueryWrapper<UserInterfaceInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInterfaceInfo::getUserId, userId);
        queryWrapper.eq(UserInterfaceInfo::getInterfaceInfoId, interfaceInfoId);
        UserInterfaceInfo userInterfaceInfo = this.getOne(queryWrapper);
        if (userInterfaceInfo == null) {
            // TODO 第一次调用，在数据库中添加数据
            UserInterfaceInfo userInterfaceInfo2DB = new UserInterfaceInfo();
            userInterfaceInfo2DB.setUserId(userId);
            userInterfaceInfo2DB.setInterfaceInfoId(interfaceInfoId);
            userInterfaceInfo2DB.setTotalNum(1);
            // 这里的剩余次数不知道怎么写
            return this.save(userInterfaceInfo2DB);
        }
        // 3. 如果存在
        LambdaUpdateWrapper<UserInterfaceInfo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(UserInterfaceInfo::getUserId, userId);
        updateWrapper.eq(UserInterfaceInfo::getInterfaceInfoId, interfaceInfoId);
        updateWrapper.gt(UserInterfaceInfo::getLeftNum, 0);
        updateWrapper.setSql("leftNum = leftNum - 1, totalNum = totalNum + 1");
        return this.update(updateWrapper);
    }

    @Override
    public List<InterfaceInfoVO> listTopInvokeInterfaceInfo() {
        // 1. 查出调用次数最多的前3条接口的id和调用次数
        List<UserInterfaceInfo> userInterfaceInfoList = this.baseMapper.listTopInvokeInterfaceInfo(3);
        // 2. 分组 Long 为 interfaceInfoId value 为 userInterfaceInfoList
        Map<Long, List<UserInterfaceInfo>> interfaceInfoObjMap
                = userInterfaceInfoList.stream().collect(Collectors.groupingBy(UserInterfaceInfo::getInterfaceInfoId));
        // 2. 根据接口id查出接口详细信息
        LambdaQueryWrapper<InterfaceInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(InterfaceInfo::getId, interfaceInfoObjMap.keySet());
        List<InterfaceInfo> interfaceInfoList = interfaceInfoService.list(wrapper);
        if (CollectionUtils.isEmpty(interfaceInfoList)) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 3. 将interfaceInfo 转成 interfaceInfoVo
        List<InterfaceInfoVO> interfaceInfoVOList = interfaceInfoList.stream().map(item -> {
            InterfaceInfoVO interfaceInfoVO = new InterfaceInfoVO();
            BeanUtils.copyProperties(item, interfaceInfoVO);
            interfaceInfoVO.setTotalNum(interfaceInfoObjMap.get(item.getId()).get(0).getTotalNum());
            return interfaceInfoVO;
        }).collect(Collectors.toList());
        return interfaceInfoVOList;
    }
}




